<?php
namespace App\Models;

use App\Traits\Fun;
use Illuminate\Database\Eloquent\Model;

class Permission extends Model
{
    use Fun;

    // 访问器  menu Menu
    public function getMenuAttribute() {
        return $this->is_menu == '1' ?'<span class="label label-success radius">是</span>' : '<span class="label label-danger radius">否</span>';
    }

    /**
     * 获取全部的数据
     * @return array
     */
    public function list() {
        $data = self::get()->toArray();
        return $this->tree($data);
    }

    /**
     * 获取层级的数据
     * @param $data array 用户有的权限
     * @return array
     */
    public function treeData($data = []) {
        // 获取权限
        $list = self::select('id','parent_id', 'display_name as title')->get()->toArray();
        foreach ($list as $key => $val) {
            $list[$key]['field']   = 'permission_ids[]';
            $list[$key]['checked'] = isset($data) ? in_array($val['id'],$data) : false;
            $list[$key]['spread']  = $val['parent_id']==0;
        }
        return $this->subTree($list);
    }

    /**
     * 菜单列表
     * @return array
     */
    public function menuData()
    {
        $data = self::where('status', '1')
            ->orderBy('sort','desc')
            ->get()->toArray();
        foreach ($data as $k=>$v){
            $data[$k]['icon_class'] = $v['icon'];
            unset($data[$k]['icon']);
        }
        return $this->subTree($data);
    }

    //子权限
    public function children()
    {
        return $this->hasMany('App\Models\Permission','parent_id','id');
    }

    //获取一二级
    public function sub()
    {
        return self::with([
            'children'=>function($query){},
        ])->where('parent_id',0)->orderBy('sort','desc')->get();
    }
}
